import threading



from core.proxy.local_proxy import start_local_proxy

class ProxyManager:
    _instance = None
    _lock = threading.Lock()
    _port_counter = 8889
    _active_proxies = {}  # 存储活动的代理信息 {port: thread}

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance
    
    def get_available_port(self):
        with self._lock:
            while self._port_counter in self._active_proxies:
                self._port_counter += 1
            return self._port_counter
    
    def create_local_proxy(self, target_proxy, proxy_user, proxy_pass):
        local_port = self.get_available_port()
        proxy_thread = threading.Thread(
            target=start_local_proxy,
            args=(local_port, target_proxy, proxy_user, proxy_pass)
        )
        proxy_thread.daemon = True  # 设置为守护线程
        proxy_thread.start()
        
        self._active_proxies[local_port] = proxy_thread
        print(f"启动本地代理: {local_port} -> {target_proxy}")
        return local_port
    
    def remove_proxy(self, local_port):
        """停止并移除代理"""
        if local_port in self._active_proxies:
            try:
                proxy_thread = self._active_proxies[local_port]
                proxy_thread.stop_flag = True
                proxy_thread.join(timeout=5)
                del self._active_proxies[local_port]
                print(f"已停止并移除本地代理: {local_port}")
            except Exception as e:
                print(f"移除代理时发生错误: {e}")
                self._active_proxies.pop(local_port, None)